package com.tanhua.server.service.impl;

import com.tanhua.autoconfig.properties.HuanXinProperties;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.LikeCount;
import com.tanhua.model.dto.UserDto;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.intercepter.UserThreadLocal;
import com.tanhua.server.service.UserFreezeService;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserServise;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserServise {

    //redis缓存注入
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信
    @Autowired
    private SmsTemplate smsTemplate;

    //db service接口
    @DubboReference
    private UserApi userApi;


    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private UserFreezeService userFreezeService;

    @DubboReference
    private UserLikeApi userLikeApi;


    /**
     * 发送验证码
     */
    @Override
    public ResponseEntity sendSms(String phone) {
        //1.获取电话
        //2.首先检验该用户状态是否被冻结
        User user = userApi.findByMobile(phone);
        if (user != null) {
            //3.调用service查看用户是否被限制登录
            userFreezeService.checkUserStatus(1, user.getId());
        }
        //4.获取6位数字验证码
        //  String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        System.out.println(code);
        //调用工具类发短信,传入phone+code
        //smsTemplate.sendSms(phone, code);

        //存到redis,时间设置5分钟,5分钟后自动销毁,
        redisTemplate.opsForValue().set("LOGIN_CODE" + phone, code, Duration.ofMinutes(5));
        return ResponseEntity.ok(null);
    }

    /**
     * 用户登录
     */
    @Override
    public UserVo loginUser(String phone, String code) {
        //1.调用redis中的code
        String codeRedis = redisTemplate.opsForValue().get("LOGIN_CODE" + phone);
        //2.比对两个code是否相等
        if (StringUtils.isEmpty(code) || !code.equals(codeRedis)) {
            //无效验证码
            throw new BusinessException(ErrorResult.loginError());
        }
        //比对通过时,删除验证码
        redisTemplate.delete("LOGIN_CODE" + phone);

        //3.通过电话查询数据库,判断该用户是否注册过
        boolean isNew = false;
        User user = userApi.findByMobile(phone);
        //当用户第一次登录时,注册
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            //初始密码 123456
            user.setPassword(DigestUtils.md5Hex("123456"));
            //注册新用户,返回该用户的注册id
            Long id = userApi.save(user);
            //将id设置到新用户,方便下面生成token调用
            user.setId(id);
            //新用户为 true
            isNew = true;

            //注册环信用户
            //设置环信id
            String hxUser = "hx" + user.getId();
            Boolean user1 = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (user1) {
                //封装环信数据
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                //调用api更新user数据
                userApi.update(user);
            }
        }
        //4. 登录成功, 生成token
        Map<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("id", user.getId());
        tokenMap.put("phone", phone);
        String token = JwtUtils.getToken(tokenMap);

        //5. 封装(token,isNew)数据返回用户
        UserVo userVo = UserVo.builder()
                .isNew(isNew)
                .token(token)
                .build();
        return userVo;
    }


    /**
     * 修改手机号1:发送验证码
     */
    @Override
    public void sendSmsCode() {
        //1.获取线程里面的电话
        String phone = UserThreadLocal.getPhone();
        //4.获取6位数字验证码
        //  String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        System.out.println(code);
        //调用工具类发短信,传入phone+code
        //smsTemplate.sendSms(phone, code);

        //存到redis,时间设置5分钟,5分钟后自动销毁,
        redisTemplate.opsForValue().set("CODE_" + phone, code, Duration.ofMinutes(5));
    }


    /**
     * 修改手机号码2:校验手机号码
     */
    @Override
    public ResponseEntity checkVerificationCode(String code) {
        //1.从线程获取用户电话
        String phone = UserThreadLocal.getPhone();

        String codeRedis = redisTemplate.opsForValue().get("CODE_" + phone);
        //2.判断验证码是否正确
        if (codeRedis.isEmpty() || code.isEmpty() || !code.equals(codeRedis)) {
            //2.1无效验证码
            throw new BusinessException(ErrorResult.loginError());
        }
        //如果验证码正确删除,缓存验证码
        Boolean flag = null;
        if (code.equals(codeRedis)){
            //检验正确删除验证码
            redisTemplate.delete("LOGIN_CODE" + phone);
             flag = true;
        }
        //构造返回值
        HashMap<String, Object> map = new HashMap<>();
        map.put("verification", flag);

        return ResponseEntity.ok(map);
    }



    /**
     * 修改手机号3:修改手机号
     */
    @Override
    public void updatePhone(String phone) {
        //获取用户的id
        Long userId = UserThreadLocal.getUserId();
        //根据用户id修改电话
        userApi.updatePhone(phone, userId);
    }


    /**
     * 是否喜欢
     *
     * @param id
     * @return
     */
    @Override
    public Boolean alreadyLove(Long id) {

    // ??
        return true;
    }

    /**
     * 我的-统计 互相喜欢、喜欢、粉丝 数量
     *
     */
    @Override
    public LikeCount counts() {
        //获取本用户的id
        Long userId = UserThreadLocal.getUserId();
        return userLikeApi.counts(userId);
    }


}
